package cn.xtcode.domain.activity.service.trial.node;

import cn.xtcode.domain.activity.adapter.repository.IActivityRepository;
import cn.xtcode.domain.activity.model.entity.MarketProductEntity;
import cn.xtcode.domain.activity.model.entity.TrialBalanceEntity;
import cn.xtcode.domain.activity.model.valobj.ActivityVEVO;
import cn.xtcode.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import cn.xtcode.domain.activity.service.trial.AbstractGroupBuyMarketSupport;
import cn.xtcode.domain.activity.service.trial.factory.DefaultActivityStrategyFactory;
import cn.xtcode.domain.tag.adapter.repository.ITagRepository;
import cn.xtcode.types.design.framework.tree.StrategyHandler;
import cn.xtcode.types.enums.ResponseCode;
import cn.xtcode.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author xt-code
 * @Description:
 * @Create 2025/5/8 16:07
 */
@Service
@Slf4j
public class TagNode extends AbstractGroupBuyMarketSupport<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> {
    @Resource
    private EndNode endNode;


    @Override
    protected TrialBalanceEntity doApply(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        //获取活动配置信息，获取tag_id、tag_scope[人群标签的作用]。这个活动对该标签的人会采取一些行动，行动由1、2指出
        GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = dynamicContext.getGroupBuyActivityDiscountVO();
        String tagId = groupBuyActivityDiscountVO.getTagId();
        String tagScope = groupBuyActivityDiscountVO.getTagScope();

        //1.本活动没有限制tag_id，所有用户均可参与
        if (StringUtils.isBlank(tagId)) {
            dynamicContext.setVisible(true);
            dynamicContext.setEnable(true);
            return router(requestParameter, dynamicContext);
        }

        boolean isWithin = repository.isTagCrowRange(tagId, requestParameter.getUserId());

        if(!isWithin){
            dynamicContext.setVisible(false);
            dynamicContext.setEnable(false);
            return router(requestParameter, dynamicContext);
        }
        //2.拥有tag_id。查看活动默认对拥有改标签用户的限制
        ActivityVEVO judgeVisibleAndEnable = groupBuyActivityDiscountVO.isJudgeVisibleAndEnable();

        if(judgeVisibleAndEnable == null){
            throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode());
        }


        //4.硬核指南
        dynamicContext.setVisible(judgeVisibleAndEnable.isVisible());
        dynamicContext.setEnable(judgeVisibleAndEnable.isEnable());
        return router(requestParameter, dynamicContext);
    }

    @Override
    public StrategyHandler<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> get(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        return endNode;
    }
}
